//
//  OauthViewController.swift
//  SinaWeibo
//
//  Created by 小果 on 16/2/9.
//  Copyright © 2016年 小果. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 授权控制器
class OauthViewController: UIViewController ,UIWebViewDelegate{
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        // 让根视图就是webView
        view = webView
        
        webView.delegate = self
        
        // 设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
    // 关闭
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 自动填充用户的信息
    @objc private func autoFill(){
        let js = "document.getElementById('userId').value = 'xiao66guo@163.com';" + "document.getElementById('passwd').value = 'wei!@#xiao1989gu';"
        // 执行JavaScript脚本
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

       webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl))
    }
    
    // MARK: - UIWebViewDelegate
    // 该代理方法有Bool类型的返回值，返回true通常是一切正常
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        let urlString = request.URL!.absoluteString
        // 1、在此判断request.url 的前半部分是否是回调地址，如果不是，就继续加载
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri){
            // 继续加载
            return true
        }
        
        print(request.URL!.query)
        // 2、如果是回调地址，就检查 query，查询字符串是否包含“code=",(query 就是URL中 ‘？’后面的内容
        if let query = request.URL!.query where query.hasPrefix("code="){
            // 3、如果有就截取“code="后面的字符串
            let code = query.substringFromIndex("code=".endIndex)
//            printLog(code)
            
            // 4. 调用网络方法，获取 token
            userAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                printLog(error)
                }, completed: { () -> Void in
                    printLog("登录完成！")
                    // 关闭控制器
                    SVProgressHUD.dismiss()
                    // 动画完成之后，再切换根视图控制器的操作可以保证视图控制器能够完全的销毁
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        // 通知是同步的，动画完成之后发出通知
                        NSNotificationCenter.defaultCenter().postNotificationName(XGSwiftRootViewControllerNotification, object: "Main")
                    })
            })
            
        }else{
            print("取消")
        }
        return false
    }
    
    ///  webView的代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
